"""
File: example_1.py
Project: 活动1
File Created: 2020/02/11 14:07:01
Author: Dunmore (fovd2020@outlook.com)
-----------------------------------------------------------------
Description:
1.2.1 活动1
python写excel文件
教材中的xlrd/xlwt库，因为已经很久没有更新了，所以后面多加了xlwings的实现
官方文档:https://docs.xlwings.org/en/stable/index.html
-----------------------------------------------------------------
"""
import os
import xlwt

# 获取文件所在的路径
currrent_dir = (
    os.path.dirname(__file__) if "__file__" in locals() else os.getcwd()
)

data = [
    {"name": "张三", "vote": 12},
    {"name": "李四", "vote": 22},
    {"name": "王小明", "vote": 13},
    {"name": "韩梅梅", "vote": 67},
    {"name": "陈建国", "vote": 10},
]

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet1")

# 在A1和B2单元格写入标题
sheet.write(0, 0, "姓名")
sheet.write(0, 1, "得票数")

# xlwt的行计数是从0开始的，所以数据从行1开始写入
for row, d in enumerate(data, start=1):
    sheet.write(row, 0, d["name"])
    sheet.write(row, 1, d["vote"])

workbook.save(os.path.join(currrent_dir, "excel_1.xls"))

# 更新的xlwings的实现，但海龟编辑器好像不支持
#
# import xlwings
# app = xlwings.App(visible=False)
# workbook = app.books.add()

# sheet = workbook.sheets["Sheet1"]

# sheet.range("A1").value = "姓名"
# sheet.range("B1").value = "得票数"

# for row, d in enumerate(data, start=2):
#     sheet.range(f"A{row}").value = d["name"]
#     sheet.range(f"B{row}").value = d["vote"]

# workbook.save(os.path.join(currrent_dir, "1_2_1_1.xlsx"))
# workbook.close()
# app.quit()
